/**   
 * @Title: HtmlEncode.java 
 * CopyRight(c)2010-DMX 
 */
package com.dmx.fw.web.util;

import java.util.StringTokenizer;

/** 
 * @Description: 字符串中的& < > "进行转义
 * @author: system
 * @date: 2006
 * @version V1.0 
 * 
 */
public class HtmlEncode {
	public static String encodeTextAsHTML(String pText) {
		StringTokenizer tokenizer = new StringTokenizer(pText, "&<>\"", true);
		int tokenCount = tokenizer.countTokens();

		/* no encoding's needed */
		if (tokenCount == 1)
			return pText;

		/*
		 * text.length + (tokenCount * 6) gives buffer large enough so no
		 * addition memory would be needed and no costly copy operations would
		 * occur
		 */
		StringBuffer buffer = new StringBuffer(pText.length() + tokenCount * 6);
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();
			if (token.length() == 1) {
				switch (token.charAt(0)) {
				case '&':
					buffer.append("&amp;");
					break;
				case '<':
					buffer.append("&lt;");
					break;
				case '>':
					buffer.append("&gt;");
					break;
				case '"':
					buffer.append("&quot;");
					break;
				default:
					buffer.append(token);
				}
			} else {
				buffer.append(token);
			}
		}
		return buffer.toString();
	}

}
